var paramJsonEditor;
var resultJsonEditor;
var expressionValue;


$(function () {
//初始化方法
    $("#noPlanAlert").hide();
    $("#addComponentPage").hide();
    $("#addPlanPage").hide();

    plan.getTestPlanTree();
//绑定保存按钮事件,id选择器
    $("#savePlan").click(function () {
        plan.saveTestPlan();
    });
    $("#addTestPlan").click(function () {
        plan.addTestPlan();
    })
    $("#scheduleTask").change(function () {
        plan.switchTask(this.value)
    })
    $("#componentId").change(function () {
        plan.searchComponent(this.value)
    })
    $("#addComponent").click(function () {
        plan.addComponent();
    });
    $("#saveComponentTestCase").click(function () {
        plan.saveComponentTestCase()
    });
    $("#deleteComponentTestCase").click(function () {
        plan.deleteComponentTestCase()
    });
    $("#assertType").change(function () {
        switchExpression(this.value);
    });

    $("#runTestPlan").click(function () {
        plan.runTestPlan()
    });
    $("#invoke").click(function () {
        var interfaceId = $("#componentId").val();
        var param = JSON.stringify(paramJsonEditor.get());
        invokeForTestPlan(interfaceId, param);
    });

    expressionValue = new ExpressionValueUtil();
    expressionValue.init($("#expressionTable"), $("#addExpression"), 150);


    paramJsonEditor = initJsonEditor("param", "tree");
    resultJsonEditor = initJsonEditor("result", "tree");
})


var plan = {
    /**
     * 新增测试接口
     * **/
    addComponent: function () {
        var testPlanTree = $.fn.zTree.getZTreeObj("testPlanTree");
        if (testPlanTree == null) {
            Ewin.alert("您还没有测试计划哦,请创建测试计划");
            return
        }
        var nodes = testPlanTree.getSelectedNodes();
        if (nodes.length == 0) {
            Ewin.alert("请选择一个测试计划,在创建组件");
            return
        }
        var node = nodes[0];
        if (node.type != "testPlan") {
            Ewin.alert("只能在测试计划下创建组件");
            return
        }
        var testPlanId = node.id;
        /**设置选择的测试计划id，用户提交组件使用**/
        $("#testPlanId").val(testPlanId);
        $("#testPlanDetailId").val('');
        plan.initComponent();
        $("#addComponentPage").show();
        $("#addPlanPage").hide();
        switchExpression(1);
        extractorExpression(1);
        $("#extractorType").val(-1);
        $("#assertType").val(1);
        expressionValue.removeAll();
        extractorValue.removeAll();
        // $("#expressionTable").bootstrapTable('load',[]);
        // $("#extractorTable").bootstrapTable('load',[]);
    },
    /**
     * 初始化当前项目里面所有组件的信息
     * **/
    initComponent: function () {
        var url = "/testPlan/componentListForPlan";
        $.ajax({
            url: url,
            method: "get",
            async: false,
            success: function (result) {
                if (result.success) {
                    var componentList = result.data;
                    var i = 0;
                    var firstValue;
                    $("#componentId").empty();
                    componentList.forEach(function (component) {
                        var value = component.id;
                        if (i == 0) {
                            firstValue = value;
                            plan.searchComponent(value);
                            i++;
                        }
                        var option = "<option   value='" + value + "'>" + component.interfaceAliasName + "</option>"
                        $("#componentId").append(option);
                    });
                    $("#componentId").val(firstValue).select2();
                } else {
                    Ewin.alert(result.msg)
                }
            }
        })
    },
    /**
     * 查询组件和测试用例
     * **/
    searchComponent: function (id) {
        var url = "/testPlan/getComponentAndTestCase";
        $.ajax({
            url: url,
            method: "get",
            async: false,
            data: {
                id: id
            },
            success: function (result) {
                if (result.success) {
                    var testPlanBuild = result.data;
                    var component = testPlanBuild.protocol;
                    $("#interfaceAliasName").text(component.interfaceAliasName);
                    $("#interfaceName").text(component.interfaceName);
                    $("#interfaceMethod").text(component.interfaceMethod);
                    $("#encoding").text(component.encoding);
                    $("#timeout").text(component.timeout);
                    $("#userName").text(component.userName);
                    var data = testPlanBuild.testCaseList;
                    var runMode = plan.getRunMode();
                    if (runMode == 1) {//如果单个接口执行,则初始化用例列表
                        plan.initTestCase(data);
                    } else {//如果是接口串联，则获取接口的参数模板
                        plan.initSuiteTestCase(component.param);
                    }
                } else {
                    Ewin.alert(result.msg)
                }
            }
        })
    },
    deleteComponentTestCase:function(){
        var url = "/testPlan/deleteComponentTestCase";
        var testPlanDetailId = $("#testPlanDetailId").val();
        $.ajax({
            type: "post",
            url: url,
            async: false,
            data: {
                id: testPlanDetailId
            },
            success: function (result) {
                if (result.success) {
                    /**刷新当前页面**/
                    window.location.reload();
                } else {
                    Ewin.alert(result.msg)
                }
            }
        });
    },
    /**
     * 保存选择的组件和测试用例
     * **/
    saveComponentTestCase: function () {
        var interfaceId = $("#componentId").val();
        var interfaceAliasName = $("#componentId").find("option:selected").text();
        var testPlanId = $("#testPlanId").val();
        var testPlanDetailId = $("#testPlanDetailId").val();
        var runMode = plan.getRunMode();

        if (runMode == 2) {
            var param = JSON.stringify(paramJsonEditor.get());
            var expectResult = JSON.stringify(resultJsonEditor.get());
            var assertType = $("#assertType").val();
            var expressionData = $("#expressionTable").bootstrapTable("getData");
            var expression = JSON.stringify(expressionData);
            var extractorType = $("#extractorType").val();
            var extractorData = $("#extractorTable").bootstrapTable("getData");
            var extractor = JSON.stringify(extractorData);
            var url = "/testPlan/saveSuiteComponentTestCase";
            $.ajax({
                type: "post",
                url: url,
                async: false,
                data: {
                    id: testPlanDetailId,
                    interfaceAliasName: interfaceAliasName,
                    interfaceId: interfaceId,
                    testPlanId: testPlanId,
                    param: param,
                    assertType: assertType,
                    expression: expression,
                    extractorType: extractorType,
                    extractor: extractor,
                    expectResult: expectResult
                },
                success: function (result) {
                    if (result.success) {
                        /**刷新当前页面**/
                        window.location.reload();
                    } else {
                        Ewin.alert(result.msg)
                    }
                }
            });
            return;
        }
        var arrSelections = $("#dataTable").bootstrapTable("getSelections");
        if (arrSelections.length <= 0) {
            Ewin.alert("必须选择一条数据操作");
            return;
        }
        /**把所有选择的测试用例id放到一个列表里面**/
        var caseIds = [];
        for (var i = 0; i < arrSelections.length; i++) {
            caseIds.push(arrSelections[i].id)
        }

        var url = "/testPlan/saveComponentTestCase";
        $.ajax({
            type: "post",
            url: url,
            /**加上这个属性，代表可以传入数组数据**/
            traditional: true,
            data: {
                id: testPlanDetailId,
                interfaceAliasName: interfaceAliasName,
                interfaceId: interfaceId,
                testPlanId: testPlanId,
                caseIds: caseIds
            },
            success: function (result) {
                if (result.success) {
                    /**刷新当前页面**/
                    window.location.reload();
                } else {
                    Ewin.alert(result.msg)
                }
            }
        });
    },
    /**
     * 初始化组件的测试用例
     * **/
    initTestCase: function (data) {
        $("#casePage").show();
        $("#suitePage").hide();
        $("#dataTable").bootstrapTable('destroy');
        $("#dataTable").bootstrapTable({
            data: data,
            height: 500,
            cache: false,
            pagination: true,
            sortable: false,
            sortOrder: "asc",
            sidePagination: "client",
            pageNumber: 1,
            pageSize: 10,
            pageList: [10, 20, 30, 40, 50],
            paginationPreText: "上一页",
            paginationNextText: "下一页",
            showRefresh: true,
            search: true,
            clickToSelect: true,
            columns: [
                {
                    checkbox: true
                },
                {
                    "title": "用例id",
                    "field": "id"
                },
                {
                    "title": "用例名称",
                    "field": "testCaseName"
                },
                {
                    "title": "用例级别",
                    "field": "level"
                }
            ]
        })
    },
    /**
     * 初始化场景用例
     * **/
    initSuiteTestCase: function (param, expectResult) {
        $("#casePage").hide();
        $("#suitePage").show();
        if ("" != param && "undefined" != typeof (param)) {
            var o = $.parseJSON(param);
            paramJsonEditor.set(o);
        } else {
            var array = [];
            paramJsonEditor.set(array);
        }
        if ("" != expectResult && "undefined" != typeof (expectResult)) {
            var o = $.parseJSON(expectResult);
            resultJsonEditor.set(o);
        } else {
            var array = [];
            resultJsonEditor.set(array);
        }
    },

    /**
     * 获取当前测试计划的执行模式
     * **/
    getRunMode: function () {
        var testPlanTree = $.fn.zTree.getZTreeObj("testPlanTree");
        var nodes = testPlanTree.getSelectedNodes();
        var parentNode = nodes[0].getParentNode();
        var runMode;
        if (null == parentNode) {
            /**使用parentNode判断的主要目的是无法区分当前点击的是计划，还是组件**/
            /**父节点为空说明是单个接口执行的模式**/
            runMode = nodes[0].runMode;
        } else {
            runMode = parentNode.runMode;
        }
        return runMode;
    }
    ,
    /**
     * 打开新增测试计划页面
     * **/
    addTestPlan: function () {
        $("#addComponentPage").hide();
        $("#noPlanAlert").hide();
        $("#addPlanPage").show();
        $("#runTestPlan").hide();
        $("#testPlanId").val('');
        //将form表单中input元素type为button、submit、reset、hidden排除
        plan.switchTask(1);
        $("#scheduleTask").val(1);
        $("input[type='text']", '.form-horizontal').val('');
        $("textarea", '.form-horizontal').text('').val('');
        $("input[name='weekTime']").removeAttr('checked');
    },
    /**
     * 运行测试用例
     * **/
    runTestPlan:function(){
        var testPlanTree = $.fn.zTree.getZTreeObj("testPlanTree");
        var nodes = testPlanTree.getSelectedNodes();
        if (nodes.length == 0) {
            Ewin.alert("请选择一个测试计划,在创建组件");
            return
        }
        var children =nodes[0].children;
        if (children == null || children.length == 0) {
            Ewin.alert("测试计划还没有添加组件,请先添加组件");
            return
        }
        var testPlanId = $("#testPlanId").val();
        runTest.runTestPlan(testPlanId);
    }
    ,
    saveTestPlan: function () {
        var url = "/testPlan/saveTestPlan";
        //表单序列化,拿到里面的数据
        var data = $("form").serialize();
        $.ajax({
            url: url,
            method: "post",
            data: data,
            success: function (result) {
                if (result.success) {
                    /**刷新当前页面**/
                    window.location.reload();
                } else {
                    Ewin.alert(result.msg)
                }
            }
        })
    },
    /**
     *获取测试计划tree
     */
    getTestPlanTree: function () {
        var url = "/testPlan/getPlanTree";
        $.ajax({
            url: url,
            type: "post",
            dataType: "json",
            data: {}, success: function (result) {
                if (result.success) {
                    var zNodes = result.data;
                    if (zNodes.length == 0) {
                        $("#noPlanAlert").show();
                        return;
                    }
                    //初始化测试计划树
                    var testPlanTree = $.fn.zTree.init($("#testPlanTree"), planTreeSetting, zNodes);
                    var treeMenu = testPlanTree.getNodes()[0];
                    /**默认选中第一个节点**/
                    testPlanTree.selectNode(treeMenu);
                    /**默认点击第一个节点**/
                    planTreeSetting.callback.onClick(null, testPlanTree.setting.treeId, treeMenu);
                } else {

                }
            }
        })
    },
    /**
     *点击测试计划tree,回显测试计划和测试组件信息
     */
    clickPlanTree: function (event, treeId, treeMenu) {
        var type = treeMenu.type;
        /**type类型是在后端组装树节点设置的**/
        if (type == "testPlan") {
            plan.getTestPlanById(treeMenu);
        } else {
            plan.getComponentTestCase(treeMenu)
        }
    },
    /**
     * 获取测试用例
     * **/
    getTestPlanById: function (treeMenu) {
        var testPlanId = treeMenu.id;
        $("#testPlanId").val(testPlanId);
        var requestUrl = "/testPlan/getTestPlanById";
        $.post(requestUrl,
            {
                testPlanId: testPlanId
            },
            function (result, status) {
                if (result.success) {
                    var testPlan = result.data;
                    $("#testPlanId").val(testPlan.id); //注意这里要与隐藏标签
                    $("#testPlanName").val(testPlan.testPlanName);
                    $("#runMode").val(testPlan.runMode);
                    var scheduleTask = testPlan.scheduleTask;
                    $("#scheduleTask").val(scheduleTask);
                    plan.switchTask(scheduleTask);
                    $("#hhTime").val(testPlan.hhTime);
                    $("#mmTime").val(testPlan.mmTime);
                    $("#sendTo").val(testPlan.sendTo);
                    $("#description").val(testPlan.description);
                    var weekTime = testPlan.weekTime;
                    if (null != weekTime) {
                        var week = weekTime.split(',');
                        week.forEach(function (value) {
                            $("input[name='weekTime'][value='" + value + "']").attr("checked", "checked");
                        })
                    }
                    $("#addPlanPage").show();
                    $("#runTestPlan").show();
                    $("#addComponentPage").hide();
                }
            }, "json");
    },
    /**
     * 是否启用定时任务
     * **/
    switchTask: function (value) {
        if (value == 2) {
            $("#taskForm").hide();
        } else {
            $("#taskForm").show();
        }
    },

    /**
     * 获取组件节点和测试用例
     * **/
    getComponentTestCase: function (treeNode) {
        var testPlanDetailId = treeNode.id;
        var url = "/testPlan/getComponentTestCaseById";
        $.ajax({
            type: "post",
            url: url,
            /**加上这个属性，代表可以传入数组数据**/
            traditional: true,
            data: {
                testPlanDetailId: testPlanDetailId
            },
            success: function (result) {
                if (result.success) {
                    /**初始化组件信息**/
                    // plan.initComponent();
                    var testPlanDetail = result.data;
                    var testPlanDetailId = testPlanDetail.id;
                    $("#testPlanDetailId").val(testPlanDetailId);
                    var interfaceId = testPlanDetail.interfaceId;
                    // $("#componentId").val(interfaceId).select2();
                    var option = "<option   value='" + testPlanDetailId + "'>" + testPlanDetail.interfaceAliasName + "</option>"
                    $("#componentId").append(option);

                    plan.searchComponent(interfaceId);

                    $("#addPlanPage").hide();
                    $("#addComponentPage").show();
                    var runMode = plan.getRunMode();
                    if (runMode == 2) {
                        plan.initSuiteTestCase(testPlanDetail.param, testPlanDetail.expectResult);
                        $("#expressionDiv").empty();
                        var assertType = testPlanDetail.assertType;
                        $("#assertType").val(testPlanDetail.assertType);
                        switchExpression(assertType);
                        var expression = testPlanDetail.expression;
                        if (expression != "") {
                            expressionValue.removeAll();
                            expressionValue.loadData(testPlanDetail.expression)
                        }
                        $("#extractorType").val(testPlanDetail.extractorType);
                        extractorExpression(testPlanDetail.extractorType);
                        var extractor = testPlanDetail.extractor;
                        if (extractor != "") {
                            extractorValue.removeAll();
                            extractorValue.loadData(extractor)
                        }
                        return;
                    }
                    var testCaseIds = JSON.parse(testPlanDetail.testCaseIds);
                    var data = $('#dataTable').bootstrapTable('getData');
                    testCaseIds.forEach(function (value) {
                        var index = 0;
                        data.forEach(function (v) {
                            if (value == v.id) {
                                $('#dataTable').bootstrapTable('check', index);
                            }
                            index++;
                        });
                    });
                } else {
                    Ewin.alert(result.msg)
                }
            }
        });
    }

};
var planTreeSetting = {
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        onClick: plan.clickPlanTree
    }
};
